<?php
/* Class queries.php
*  Contains all the queries needed in 
*  each module, program or class of
*  SINAPSIS
*/
require_once($root_path.'include/care_api_classes/class_core.php');

class Queries_interconsulta extends Core{
	
		/**#@+
	* @access private
	*/
	/**
	* Table name for interconsulta
	* @var string
	*/
        var $tb_interconsulta='care_interconsulta_interconsulta';
	/**
	* Table names for foreign keys
	* @var string
	*/
        var $tb_preg_resp='care_interconsulta_preguntas_respuestas';

	var $tb_person='care_person';
	
	var $tb_adjunto='care_interconsulta_adjuntos';

	var $tb_users='care_users';
	
	var $tb_especialidad='care_interconsulta_especialidad';
	
	var $tb_paciente='care_interconsulta_paciente';

        var $tb_datos_paciente='care_interconsulta_datos_paciente';

        var $tb_grupo='care_interconsulta_grupo_triaje';

        var $tb_espeusuario='care_interconsulta_usuarioPerteneceEspecialidad';

        var $tb_bitacora='care_interconsulta_bitacora';

	/**
	* SQL query
	*/
	var $sql;
	/**#@-*/
	/**
	* PID number
	* @var int
	*/
	var $id;
	/**
	* Sql query result buffer
	* @var adodb record object
	*/
	var $result;
	/**
	* Universal flag
	* @var boolean
	*/
	var $ok;
	/**
	* Internal data buffer
	* @var array
	*/
	var $data_array;
	/**
	* Internal data buffer 2
	* @var array
	*/
	var $data2_array;
	/**
	* Universal buffer
	* @var mixed
	*/
	var $buffer;
	/**
	* Returned row buffer
	* @var array
	*/
	var $row;
	/**
	* Returned interconsulta data buffer
	* @var array
	*/
	var $interconsulta=array();
        /**
	* Returned person data buffer
	* @var array
	*/
	var $person=array();
	/**
	* Preloaded data flag
	* @var boolean
	*/
	var $is_preloaded=false;
	/**
	* Valid number flag
	* @var boolean,
	* @var array
	*/
	var $basic_list='id,id_paciente, id_especialidad, fecha_hora_consulta, establecimiento, motivo, justificacion, enfermedad_actual, examen_fisico, peso, talla, presion_arterial, temp, respiratoria, pulso, login_consultante, login_consultado, fecha_hora_respuesta, respuesta, diagnostico, tratamiento, observaciones, IDx, pauta_terapeutica, id_datos_paciente, comentarios, comentarios_resp, estado, motivo_cierre, clasificacion, interconsultas_previas,traslado,noadherencia,comentarios_clasif';

	/**
	* Field names of table care_person
	* @var array
	*/
	var  $elems_array=array(
				'id',
				 'id_paciente',
				 'id_especialidad',
				 'establecimiento',
                                 'fecha_hora_consulta',
                                 'motivo',
				 'justificacion',
                                 'enfermedad_actual',
				 'examen_fisico',
				 'peso',
				 'talla',
				 'presion_arterial',
				 'temp',
				 'respiratoria',
				 'pulso',
				 'login_consultante',
				 'login_consultado',
                                 'fecha_hora_respuesta',
				 'respuesta',
                                 'diagnostico',
                                 'tratamiento',
                                 'observaciones',
				 'IDx',
				 'pauta_terapeutica',
				 'id_datosPaciente',
                                 'comentarios',
                                 'comentarios_resp',
                                 'estado',
                                 'motivo_cierre',
				'clasificacion',
				'interconsultas_previas',
				'traslado',
				'noadherencia',
				'comentarios_clasif');
	var  $elems2_array=array('id',
				'apellido_1',
				'apellido_2',
				'name_1',
				'name_2',
				'sex',
				'etnia');
				
	function Queries_interconsulta ($id='') {
		   $this->id=$id;
	       $this->ref_array=$this->elems_array;
	       $this->coretable=$this->tb_interconsulta;
	}

	/**
	* Sets the ID number.
	* @access public
	* @param int ID number
	*/
	function setID($id) {
	    $this->id=$id;
	}

	/**
	* Prepares the internal buffer array for insertion routine.
	* @access private
	*/
	function prepInsertArray(){
            global $_POST;
		$x='';
		$v='';
		$this->data_array=NULL;
		$this->data2_array=NULL;

		while(list($x,$v)=each($this->elems_array)) {
	    	if(isset($_POST[$v])&&!empty($_POST[$v])) $this->data_array[$v]=$_POST[$v];
	    }
		while(list($x,$v)=each($this->elems2_array)) {
	    	if(isset($_POST[$v])&&!empty($_POST[$v])) $this->data2_array[$v]=$_POST[$v];
	    }

    }	
	/**
	* Inserts the data into the care_person table.
	* @access private
	* @param int PID number
	* @return boolean
	*/
    function insertDataFromArray() {
		global $db;
		$array =$this->data_array;
		$array2 =$this->data2_array;
		$x='';
		$v='';
		$index='';
		$values='';

		if(is_array($array)){

			if(is_array($array2)){ //Inserto los datos del paciente de la interconsulta
				while(list($x,$v)=each($array2)) {
					$index.="$x,";
					$values.="'$v',";
				}
				$index=substr_replace($index,'',(strlen($index))-1);
				$values=substr_replace($values,'',(strlen($values))-1);
		
				$this->sql="INSERT INTO $this->tb_datos_paciente ($index) VALUES ($values)";

				$a=$this->Transact();

				if($a){
					$this->sql=" SELECT LAST_INSERT_ID()";
					if($this->result=$db->Execute($this->sql)) {
						if($this->result->RecordCount()) {
							$res= $this->result->FetchRow();
							$id_datos = $res['LAST_INSERT_ID()'];
						}
					}
				}
			}

			$x='';
			$v='';
			$index='';
			$values='';
			if($id_datos){
				$index.='id_datos_paciente, ';
				$values.="'$id_datos', ";
			}

			while(list($x,$v)=each($array)) {
				$index.="$x,";
				$values.="'$v',";
			} 
			$index=substr_replace($index,'',(strlen($index))-1);
			$values=substr_replace($values,'',(strlen($values))-1);
	
			$this->sql="INSERT INTO $this->tb_interconsulta ($index) VALUES ($values)";
	
			// 			echo $this->sql;
			$b = $this->Transact();

                        if($b){
                            $this->sql="SELECT LAST_INSERT_ID()";
                            if($this->result=$db->Execute($this->sql)) {
                                if($this->result->RecordCount()) {
                                    $res= $this->result->FetchRow();
                                    $this->id = $res['LAST_INSERT_ID()'];
                                }
                            }
                        }

		}else{
			return false;
		}

		return true;
	}

	/**
	* Inserts the data from the internal buffer array into the care_person table.
	*
	* The data must be packed in the buffer array with index keys as outlined in the <var>$elems_array</var> array.
	* @access public
	* @return boolean
	*/
	function insertDataFromInternalArray() {
            global $_POST;
	    //$this->data_array=NULL;
		$this->prepInsertArray();
		return $this->insertDataFromArray();
	}


	function updateDataFromInternalArray($idInter) {
		global $_POST;

                $this->id = $idInter;
		$this->prepInsertArray();
		return $this->updateDataFromArray($this->data_array,$idInter);
	}


    function updateDataFromArray(&$array,$item_nr='') {
		$x='';
		$v='';
		$sql='';
		
		if(!is_array($array)) return false;
		if(empty($item_nr)||!is_numeric($item_nr)) return false;
		while(list($x,$v)=each($array)) {
			if(stristr($v,'concat')||stristr($v,'null')) $sql.="$x= $v,";
		    	else $sql.="$x='$v',";
		}
		$sql=substr_replace($sql,'',(strlen($sql))-1);
		
        $this->sql="UPDATE $this->tb_interconsulta SET $sql WHERE id=$item_nr";
// 		echo $this->sql;
		return $this->Transact();
	}

	/**
	* Resolves the ID number to be used in the methods.
	* @access public
	* @param int ID number
	* @return boolean
	*/
	function internResolveID($id) {
	    if (empty($id)) {
		    if(empty($this->id)) {
			    return false;
			} else { return true; }
		} else {
		     $this->id=$id;
			return true;
		}
	}
	
	/**
	* Checks if ID number exists in the database.
	* @access public
	* @param int ID number
	* @return boolean
	*/
	function InitIDExists($init_nr){
		global $db;
		$this->sql="SELECT id FROM $this->tb_interconsulta WHERE id=$init_nr";
		if($this->result=$db->Execute($this->sql)){
			if($this->result->RecordCount()){
				return true;
			} else { return false; }
		} else { return false; }
	}

	/**
	* Database transaction. Uses the adodb transaction method.
	* @access private
	*/
	function Transact($sql='') {

	    global $db;
	    //$db->debug=true;
        if(!empty($sql)) $this->sql=$sql;

        $db->BeginTrans();
        $this->ok=$db->Execute($this->sql);
        if($this->ok) {
            $db->CommitTrans();
			return true;
        } else {
	        $db->RollbackTrans();
			return false;
	    }
    }	
	
	//insert data from array linea 218
	//otros de update

	//$pregResp = $query->getAllPreguntasRespuestas($id);
	function getAllPreguntasRespuestas($id){
            global $db;

            $this->sql = "SELECT * from $this->tb_preg_resp WHERE id_interconsulta=$id ORDER BY id ASC";
	//            echo $this->sql;
            if($this->result=$db->Execute($this->sql)) {
            if($this->result->RecordCount()) {
				 return $this->result;
			} else { return false; }
		} else { return false; }
	}
	

	/**
	* Gets all interconsulta information based on its ID number key.
	*
	* The returned adodb record object contains a row or array.
	* This array contains data with the following index keys:
	* - all index keys as outlined in the <var>$elems_array</var> array
	* - addr_citytown_name = name of the city or town
	*
	* @access public
	* @param int ID number
	* @return mixed adodb object or boolean
	*/
	function getAllInfoObject($id) {
	    global $db;
		 
            $this->sql="SELECT 
		i.*,
		i.login_consultado AS ico_name,
		p.apellido_1 as apellido_1, 
		p.apellido_2 as apellido_2, 
		p.name_1 as name_1, 
		p.name_2 as name_2, 
		p.sex as sex, 
		p.etnia as etniaValue, 
		esp.descripcion AS especialidad_descripcion, 
		esp.id id_especialidad, 
		u1.name AS ice_name
		FROM $this->tb_interconsulta AS i
		INNER JOIN  $this->tb_especialidad AS esp 
		ON i.id_especialidad = esp.id
		INNER JOIN $this->tb_users AS u1
		ON (i.login_consultante = u1.login_id)
		INNER JOIN $this->tb_datos_paciente AS p
		ON (i.id_datos_paciente = p.id)
		WHERE i.id=$id";

	    //echo $this->sql;
        if($this->result=$db->Execute($this->sql)) {
            if($this->result->RecordCount()) {
				 return $this->result;	 
			} else { return false; }
		} else { return false; }
	}

	/**
	* Same as getAllInfoObject() but returns a 2 dimensional array.
	*
	* The returned  data in the array have the following index keys:
	* - all index keys as outlined in the <var>$elems_array</var> array
	* - citytown = name of the city or town
	*
	* @access public
	* @param int PID number
	* @return mixed array or boolean
	*/
	function getAllInfoArray($id='') {
	    global $db;
		 $x='';
		 $v='';
		if(!$this->internResolveID($id)) return false;
		
	    $this->sql="SELECT i.*, esp.descripcion AS especialidad_descripcion, esp.id id_especialidad
					FROM $this->tb_interconsulta AS i
					LEFT JOIN  $this->tb_especialidad AS esp ON i.id_especialidad = esp.id
					WHERE i.id='$this->id' ";

        	if($this->result=$db->Execute($this->sql)) {

			if($this->result->RecordCount()) {
				return $this->row=$this->result->FetchRow();
			} else { return false; }
		} else { return false; }
	}

	/**
	* Gets a particular interconsulta based on its ID number.
	*
	* Use this preferably after the person registration data was successfully preloaded in the internal buffer with the <var>preloadPersonInfo()</var> method.
	* For details on field names of items that can be fetched, see the <var>$elems_array</var> array.
	* @access private
	* @param string Field name of the item to be fetched
	* @param int ID number
	* @return mixed string, integer, or boolean
	*/
	function getValue($item,$id='') {
	    global $db;

	    if($this->is_preloaded) {
		    if(isset($this->interconsulta[$item])) return $this->interconsulta[$item];
		        else  return false;
		} else {
		    if(!$this->internResolveID($id)) return false;
		    $this->sql="SELECT $item FROM $this->tb_interconsulta WHERE id=$this->id";
		    //return $this->sql;
           		 if($this->result=$db->Execute($this->sql)) {
                		if($this->result->RecordCount()) {
				     $this->interconsulta=$this->result->FetchRow();
				     return $this->interconsulta[$item];
			    } else { return false; }
		    } else { return false; }
		}
	}

	/**
	* Gets interconsultas based on an item list and ID number.
	*
	* For details on field names of items that can be fetched, see the <var>$elems_array</var> array.
	* Several items can be fetched at once but their field names must be separated by comma.
	* @access public
	* @param string Field names of items to be fetched separated by comma.
	* @param int ID number
	* @return mixed
	*/
	function getValueByList($list,$id='') {
	    global $db;
	
		if(empty($list)) return false;
		if(!$this->internResolveID($id)) return false;
		$this->sql="SELECT $list FROM $this->tb_interconsulta WHERE id=$this->id";
        if($this->result=$db->Execute($this->sql)) {
            if($this->result->RecordCount()) {
				$this->interconsulta=$this->result->FetchRow();	 
				return $this->interconsulta;
			} else { return false; }
		} else { return false; }
	}

	function getValueBy($login_ico, $id_esp = '', $st = '',$intero='',$intere='', $fc = '', $fr = '') {
	    global $db;


                $where = '';

                if ($id_esp != 0)
                {
                    $where = " inter.id_especialidad=$id_esp";
                }

                if ($st != 0)
                {
			if ($where){
				$where.= " AND";
			}

                    switch ($st)
                    {
                        case 1:
                            $where .= " inter.login_consultado IS NOT NULL ";
                            break;
                        case 2:
                            $where .= " inter.login_consultado IS NULL ";
                            break;
                    }
                }

                if (strlen($intero))
                {
			if ($where){
				$where.= " AND";
			}

                    $where .= " inter.login_consultado IN (SELECT login_id FROM $this->tb_users WHERE name LIKE '%$intero%')";
                }

                if (strlen($intere))
                {
			if ($where){
				$where.= " AND";
			}

                    $where .= " inter.login_consultante IN (SELECT login_id FROM $this->tb_users WHERE name LIKE '%$intere%')";
                }


                if (strlen($fc))
                {
			if ($where){
				$where.= " AND";
			}

	                    $where .= " (locate('$fc', inter.fecha_hora_consulta)!=0) ";
                }

                if (strlen($fr))
                {
			if ($where){
				$where.= " AND";
			}
	                    $where .= " (locate('$fr', inter.fecha_hora_respuesta)!=0) ";
                }

		$result=array();
		$q="SELECT ".
			"inter.id as id, inter.establecimiento as establecimiento, inter.enfermedad_actual as enfermedad_actual, inter.respuesta as respuesta, inter.login_consultante as consultante,inter.login_consultado as consultado, esp.descripcion as especialidad, paciente.name_first as paciente".
		" FROM ".
			" care_interconsulta_interconsulta AS inter".
			" INNER JOIN".
			" care_person AS paciente".
			" ON (paciente.pid=inter.id_paciente)".
			" INNER JOIN".
			" care_interconsulta_especialidad AS esp".
			" ON (inter.id_especialidad=esp.id)";

		if ($where){
			$q.= " WHERE ".$where;
		}

		//               echo $q;

		$this->sql=$q;
		if($this->result=$db->Execute($this->sql)) {
			if($this->result->RecordCount()) {
				while($temp=$this->result->FetchRow()){
					$result[]=$temp;
				}
				return $result;
			}
		} else { 
			return false; 
		}
	}

	/**
	* Gets interconsultas based on an item list and login_consultante.
	*
	* For details on field names of items that can be fetched, see the <var>$elems_array</var> array.
	* Several items can be fetched at once but their field names must be separated by comma.
	* @access public
	* @param string Field names of items to be fetched separated by comma. 
	* @param int ID number
	* @return mixed
	*/
	function getValueByConsultante($login_ico, $id_esp = '', $st = '', $intero = '', $fc = '', $fr = '') {
		global $db;

                $where = '';

                if ($id_esp != 0)
                {
                    $where = " AND inter.id_especialidad=$id_esp";
                }

                if ($st != 0)
                {
                    switch ($st)
                    {
                        case 1:
                            $where .= " AND inter.login_consultado IS NOT NULL ";
                            break;
                        case 2:
                            $where .= " AND inter.login_consultado IS NULL ";
                            break;
                    }
                }

                if (strlen($intero))
                {
                    $where .= " AND inter.login_consultado IN (SELECT login_id FROM $this->tb_users WHERE name LIKE '%$intero%')";
                }

                if (strlen($fc))
                {
	                    $where .= " AND (locate('$fc', inter.fecha_hora_consulta)!=0) ";
                }

                if (strlen($fr))
                {
	                    $where .= " AND (locate('$fr', inter.fecha_hora_respuesta)!=0) ";
                }

		$result=array();

		$q="SELECT ".
			"inter.id as id, inter.establecimiento as establecimiento, inter.motivo as motivo, inter.respuesta as respuesta, inter.login_consultante as consultante,inter.login_consultado as consultado, esp.descripcion as especialidad, paciente.name_first as paciente".
		" FROM ".
			" $this->tb_interconsulta AS inter".
			" INNER JOIN".
			" $this->tb_person AS paciente".
			" ON (paciente.pid=inter.id_paciente)".
			" INNER JOIN".
			" $this->tb_especialidad AS esp".
			" ON (inter.id_especialidad=esp.id)".
		" WHERE ".
			" inter.login_consultante='$login_ico' $where";
		//echo $q;

		$this->sql=$q;
		if($this->result=$db->Execute($this->sql)) {
			if($this->result->RecordCount()) {
				while($temp=$this->result->FetchRow()){
					$result[]=$temp;
				}
				return $result;
			}
		} else { 
			return false; 
		}
	}


    /**
	* Gets interconsultas based on an item list and login_consultado.
	*
	* For details on field names of items that can be fetched, see the <var>$elems_array</var> array.
	* Several items can be fetched at once but their field names must be separated by comma.
	* @access public
	* @param string Field names of items to be fetched separated by comma. 
	* @param int ID number
	* @return mixed
	*/
	function getValueByConsultado($login_ico, $id_esp = '', $st = '', $intere = '', $fc = '', $fr = '') {
	    global $db;

                $where = '';

                if ($id_esp != 0)
                {
                    $where = " AND inter.id_especialidad=$id_esp";
                }

                if ($st != 0)
                {
                    switch ($st)
                    {
                        case 1:
                            $where .= " AND inter.login_consultado IS NOT NULL ";
                            break;
                        case 2:
                            $where .= " AND inter.login_consultado IS NULL ";
                            break;
                    }
                }

                if (strlen($intere))
                {
                    $where .= " AND inter.login_consultante IN (SELECT login_id FROM $this->tb_users WHERE name LIKE '%$intere%')";
                }

                if (strlen($fc))
                {
	                    $where .= " AND (locate('$fc', inter.fecha_hora_consulta)!=0) ";
                }

                if (strlen($fr))
                {
	                    $where .= " AND (locate('$fr', inter.fecha_hora_respuesta)!=0) ";
                }

		$result=array();
		$q="SELECT ".
			"inter.id as id, inter.establecimiento as establecimiento, inter.enfermedad_actual as enfermedad_actual, inter.respuesta as respuesta, inter.login_consultante as consultante,inter.login_consultado as consultado, esp.descripcion as especialidad, paciente.name_first as paciente".
		" FROM ".
			" care_interconsulta_interconsulta AS inter".
			" INNER JOIN".
			" care_person AS paciente".
			" ON (paciente.pid=inter.id_paciente)".
			" INNER JOIN".
			" care_interconsulta_especialidad AS esp".
			" ON (inter.id_especialidad=esp.id)".
		" WHERE ".
			" inter.login_consultado='$login_ico' $where";
//                 echo $q;
		$this->sql=$q;
		if($this->result=$db->Execute($this->sql)) {
			if($this->result->RecordCount()) {
				while($temp=$this->result->FetchRow()){
					$result[]=$temp;
				}
				return $result;
			}
		} else { 
			return false; 
		}
	}

	/**
	* Preloads the person registration data for interconsulta in the internal buffer <var>$person</var>.
	*
	* The preload success status is stored in the <var>$is_preloaded</var> variable.
	* The buffered adodb record object contains a row or array.
	* This array contains data with index keys as outlined in the <var>$elems_array</var> array
	*
	* @access public
	* @param int PID number
	* @return boolean
	*/
	function preloadPersonInfo($pid) {
	    global $db;

                if (empty($pid)) {
		    if(empty($this->id_paciente)) {
			    return false;
			} 
		} else {
		     $this->id_paciente=$pid;
			return true;
		}
		$this->sql="SELECT * FROM $this->tb_person WHERE pid=$this->id_paciente";
        if($this->result=$db->Execute($this->sql)) {
            if($this->result->RecordCount()) {
				 $this->person=$this->result->FetchRow();	
				 $this->is_preloaded=true; 
				 return true;
			} else { return false; }
		} else { return false; }
	}

/**
	* Preloads the person registration data for interconsulta in the internal buffer <var>$person</var>.
	*
	* The preload success status is stored in the <var>$is_preloaded</var> variable.
	* The buffered adodb record object contains a row or array.
	* This array contains data with index keys as outlined in the <var>$elems_array</var> array
	*
	* @access public
	* @param int PID number
	* @return boolean
	*/
	function preloadUserInfo($login) {
	    global $db;

		$this->sql="SELECT name, matricula, clasificacion FROM $this->tb_users WHERE login_id='" . $login . "'";
//         echo $this->sql;
        if($this->result=$db->Execute($this->sql)) {
            if($this->result->RecordCount()) {
				 $user=$this->result->FetchRow();
				 return $user;
			}
		} else { return false; }
	}
    
    /**
	* loads especialidades data for interconsulta in the internal buffer <var>$person</var>.
	*
	* The preload success status is stored in the <var>$is_preloaded</var> variable.
	* The buffered adodb record object contains a row or array.
	* This array contains data with index keys as outlined in the <var>$elems_array</var> array
	*
	* @access public
	* @param int PID number
	* @return boolean
	*/
	function loadEspecialidades() {
	    global $db;

		$this->sql="SELECT * FROM $this->tb_especialidad";
        if($this->result=$db->Execute($this->sql)) {
            if($this->result->RecordCount()) {
				while($temp=$this->result->FetchRow()){
					$result[]=$temp;
				}
				return $result;
			}
		} else { return false; }
	}
    
    /**
	* loads ethnic groups data for interconsulta in the internal buffer <var>$person</var>.
	*
	* The preload success status is stored in the <var>$is_preloaded</var> variable.
	* The buffered adodb record object contains a row or array.
	* This array contains data with index keys as outlined in the <var>$elems_array</var> array
	*
	* @access public
	* @param int PID number
	* @return boolean
	*/
	function loadEtnias() {
	    global $db;

		$this->sql="SELECT nr, name FROM care_type_ethnic_orig";
        if($this->result=$db->Execute($this->sql)) {
            if($this->result->RecordCount()) {
				 return $this->result;
			}
		} else { return false; }
	}

	function loadEtnia($val) {
	    global $db;

		$this->sql="SELECT name FROM care_type_ethnic_orig WHERE nr=".$val;
        if($this->result=$db->Execute($this->sql)) {
            if($this->result->RecordCount()) {
				$temp = $this->result->FetchRow();
				 return $temp[0];
			}
		} else { return false; }
	}

    
	/**
	* get's
	*/
	function Establecimiento() {
        return $this->getValue('establecimiento');
	}
	
	function Justificacion() {
        return  $this->getValue('justificacion');
	}
	
	function ExamenFisico() {
        return  $this->getValue('examen_fisico');
	}

	function Peso() {
        return  $this->getValue('peso');
	}
	
	function Talla() {
        return  $this->getValue('talla');
	}
	
	function PresionArterial() {
        return  $this->getValue('presion_arterial');
	}
	
	function Temperatura() {
        return  $this->getValue('temp');
	}
	
	function FrecuenciaRespiratoria() {
        return  $this->getValue('respiratoria');
	}
	
	function Pulso() {
        return  $this->getValue('pulso');
	}
	
	function Consultante() {
        return  $this->getValue('login_consultante');
	}
	
	function Consultado() {
        return  $this->getValue('login_consultado');
	}
	
	function Paciente() {
        return  $this->getValue('id_paciente');
	}
	
	function Especialidad() {
        return  $this->getValue('id_especialidad');
	}

	function Evaluacion() {
        return  $this->getValue('evaluacion');
	}
	
	function IDx() {
        return  $this->getValue('IDx');
	}
	
	function PautaTerapeutica() {
        return  $this->getValue('pauta_terapeutica');
	}
	
	function DatosPaciente() {
        return  $this->getValue('id_datos_paciente');
	}

	/**
	* Returns especialidad name based on its "id" key.
	* @access public
	* @return mixed string or boolean
	*/
	function EspecialidadName($code_nr=''){
	    global $db;
	    echo "hola";
		if(!$this->is_preloaded) $this->sql="SELECT descripcion FROM $this->tb_especialidad WHERE id=$code_nr";
            else $this->sql="SELECT descripcion FROM $this->tb_especialidad WHERE id=".$this->Especialidad();
			
		//echo $this->sql;exit;
        if($this->result=$db->Execute($this->sql)) {
            if($this->result->RecordCount()) {
				 $this->row=$this->result->FetchRow();	 
				 return $this->row['descripcion'];
			} else { return false; }
		} else { return false; }
    }
	/**
	* Returns interconsulta items as listed in the <var>$basic_list</var> array based on pid key.
	*
	* The data is returned as associative array.
	* @access public
	* @param int PID number
	* @return mixed string or boolean
	*/
	function BasicDataArray($id){
        if(!$this->internResolveID($id)) return false;
		return $this->getValueByList($this->basic_list,$this->id);
	}

	function loadGrupos()
	{
		global $db;

		$this->sql="SELECT DISTINCT nombre FROM $this->tb_grupo";
		if($this->result=$db->Execute($this->sql)) {
			if($this->result->RecordCount()) {
								while($temp=$this->result->FetchRow()){
										$result[]=$temp;
								}
								return $result;
						}
				} else { return false; }
	}

	function saveUsuTriaje()
        {
            global $db, $_POST;
            extract($_POST);
            $asig = explode(":", $asigacum);

            $this->sql = "SELECT login_id FROM $this->tb_grupo WHERE nombre='$nombre'";

            if($this->result=$db->Execute($this->sql)) {
                if($this->result->RecordCount()) {
                    while($temp=$this->result->FetchRow()){
                        for($i=0;$i<count($asig)-1;$i++)
                        {
                            if (strcmp($temp['login_id'], $asig[$i]))
                            {
                                $values .= "('$nombre', '" . $asig[$i] . "'),";
                            }
                        }
                    }

//                     return $result;
                }
                else
                {
                    for($i=0;$i<count($asig)-1;$i++)
                    {
                        $values .= "('$nombre', '" . $asig[$i] . "'),";
                    }
                }

                $values=substr_replace($values,'',(strlen($values))-1);

                $this->sql = "INSERT INTO $this->tb_grupo (nombre, login_id) VALUES $values";
//                 echo $this->sql;
                return $this->Transact();
            }
            else { return false; }
        }


	function getAllAsignables(){
		global $db;
		$result=array();

		$q="SELECT ".
			"inter.id as id, inter.motivo as motivo, inter.login_consultante as consultante, esp.descripcion as especialidad, esp.id id_especialidad".
		" FROM ".
			" $this->tb_interconsulta AS inter".
			" INNER JOIN".
			" $this->tb_especialidad AS esp".
			" ON (inter.id_especialidad=esp.id)".
		" WHERE ".
			" (inter.login_consultado IS NULL OR inter.login_consultado='') AND inter.estado=1 ";
//                 echo $q;

		$this->sql=$q;
		if($this->result=$db->Execute($this->sql)) {
			if($this->result->RecordCount()) {
				while($temp=$this->result->FetchRow()){
					$result[]=$temp;
				}
				return $result;
			}
		} else { 
			return false; 
		}

	}

	function loadMedicosEspecialidad($id_especialidad, $ice_name) {
	    global $db;

		$this->sql="SELECT usr.login_id as id, usr.name as name ".
			" FROM care_interconsulta_usuarioPerteneceEspecialidad rel ".
			" INNER JOIN $this->tb_users AS usr ".
			" ON (rel.login_id=usr.login_id)".
			" WHERE rel.id_especialidad=".$id_especialidad . " AND usr.name != '$ice_name'";
        if($this->result=$db->Execute($this->sql)) {
            if($this->result->RecordCount()) {
				 return $this->result;
			}
		} else { return false; }
	}

	function asignarMedico($id,$login_id){
		global $db;

	       $this->sql="UPDATE $this->tb_interconsulta SET login_consultado='".$login_id."' WHERE id=".$id;

		return $this->Transact();

	}

        function saveEspeUsuario()
        {
            global $db, $_POST;
            extract($_POST);
            $asig = explode(":", $asigacum);

            $this->sql = "SELECT id_especialidad FROM $this->tb_espeusuario WHERE login_id='$login_id'";

            if($this->result=$db->Execute($this->sql)) {
                if($this->result->RecordCount()) {
                    while($temp=$this->result->FetchRow()){
                        for($i=0;$i<count($asig)-1;$i++)
                        {
                            if (strcmp($temp['id_especialidad'], $asig[$i]))
                            {
                                $values .= "('$login_id', '" . $asig[$i] . "'),";
                            }
                        }
                    }
//                     return $result;
                }
                else
                {
                    for($i=0;$i<count($asig)-1;$i++)
                    {
                        $values .= "('$login_id', '" . $asig[$i] . "'),";
                    }
                }

                $values=substr_replace($values,'',(strlen($values))-1);

                $this->sql = "INSERT INTO $this->tb_espeusuario (login_id, id_especialidad) VALUES $values";
//                 echo $this->sql;
                return $this->Transact();
            }
            else { return false; }
        }

        function insertarBitacora($msj)
        {
            global $db;

            $this->sql = "INSERT INTO $this->tb_bitacora (id_interconsulta, mensaje, fecha) VALUES ($this->id, '$msj', '" . date("Y-m-d") . "')";

            //echo $this->sql;

            return $this->Transact();
        }

	function cerrar($motivo, $traslado, $noadherencia, $clasif, $comentarios_clasif)
        {
            global $db;

            $this->sql = "UPDATE care_interconsulta_interconsulta SET estado = '2', motivo_cierre = '$motivo', traslado = '$traslado', noadherencia = '$noadherencia', clasificacion = '$clasif', comentarios_clasif = '$comentarios_clasif' WHERE id = '" . $this->id . "'";

             //echo $this->sql;

            return $this->Transact();
        }

        function getBitacora($id_ic)
        {
            global $db;

            $this->sql = "SELECT DISTINCT id_interconsulta, mensaje, fecha FROM $this->tb_bitacora WHERE id_interconsulta=$id_ic";

            if($this->result=$db->Execute($this->sql)) {
                if($this->result->RecordCount()) {
                    while($temp=$this->result->FetchRow()){
                        $result[]=$temp;
                    }
                    return $result;
                }
            }
            else {
                return false;
            }
        }

	function guardarAdjunto($fileInput, $resp=''){
		global $db;


		if($fileInput!=''){
			$file = fopen('/tmp/'.$fileInput,"r");
			
			while(!feof($file)){
				$imgData .= fread($file, 1024);
			}
	
			$size=filesize('/tmp/'.$fileInput);
	
			fclose($file); 
			
			$imgData = addslashes ($imgData);
			$imgData = addcslashes($imgData, "\0"); 
	
			$this->sql = "INSERT INTO $this->tb_adjunto$resp (name,size,content,id_interconsulta) VALUES ('$fileInput', $size, '$imgData',$this->id)";
	
			$this->Transact();
		}

	}

	function guardarAdjuntoPregResp($fileInput, $idPreg, $resp = ''){
		global $db;

		system("logger -t sinapsis GAPR $fileInput $resp");

		if($fileInput!=''){

			system("logger -t sinapsis opening " . $fileInput);

			$file = fopen('/tmp/'.$fileInput,"r");
			
			while(!feof($file)){
				$imgData .= fread($file, 1024);
			}
	
			$size=filesize('/tmp/'.$fileInput);
	
			fclose($file); 

			system("logger -t sinapsis closing $resp " . $fileInput);
			
			system("logger -t sinapsis " . "INSERT INTO $this->tb_adjunto$resp (name,size,content,id_interconsulta, id_preg) VALUES ('$fileInput', $size, '$imgData',$this->id, $idPreg)");
			$imgData = addslashes ($imgData);
			$imgData = addcslashes($imgData, "\0"); 
			
			

	
			$this->sql = "INSERT INTO $this->tb_adjunto$resp (name,size,content,id_interconsulta, id_preg) VALUES ('$fileInput', $size, '$imgData',$this->id, $idPreg)";
	
			system("logger -t sinapsis " . $this->sql);

			$this->Transact();
		}

	}

	function seleccionarNombreAdjuntos($id, $resp=''){
		global $db;

		$this->sql = "SELECT name FROM $this->tb_adjunto" . $resp . " WHERE id_interconsulta=".$id . " AND id_preg = 0";

		//echo $this->sql;	
		if($this->result=$db->Execute($this->sql)) {
			if($this->result->RecordCount()) {
				while($temp=$this->result->FetchRow()){
				$result[]=$temp;
				}
				return $result;
			}
		}
		else {
		return false;
		}

	}

	function seleccionarNombreAdjuntosPregResp($id, $idPreg, $resp=''){
		global $db;

		$this->sql = "SELECT name FROM $this->tb_adjunto" . $resp . " WHERE id_interconsulta=".$id . " AND id_preg = " . $idPreg;

// 		echo $this->sql;	
		if($this->result=$db->Execute($this->sql)) {
			if($this->result->RecordCount()) {
				while($temp=$this->result->FetchRow()){
				$result[]=$temp;
				}
				return $result;
			}
		}
		else {
		return false;
		}

	}


	function seleccionarAdjuntos($id,$name, $resp=''){
		global $db;

		$this->sql = "SELECT * FROM $this->tb_adjunto$resp WHERE id_interconsulta=".$id." AND name='".$name."'";

// 		echo $this->sql;	
		if($this->result=$db->Execute($this->sql)) {
			if($this->result->RecordCount()) {
				while($temp=$this->result->FetchRow()){
				$result[]=$temp;
				}
				return $result;
			}
		}
		else {
		return false;
		}

	}

	function getMail($medico){
		global $db;
	
		$this->sql="SELECT mail FROM $this->tb_users where login_id='".$medico."'";
		if($this->result=$db->Execute($this->sql)) {
			if($this->result->RecordCount()) {
				while($temp=$this->result->FetchRow()){
					$result[]=$temp;
				}
				return $result;
			}
		} else { return false; }

	}
	
	function getAllMailTriaje(){
		global $db;
	
		//$this->sql="SELECT mail FROM $this->tb_users where login_id IN (SELECT DISTINCT login_id FROM $this->tb_grupo)";
                $this->sql="SELECT mail FROM $this->tb_users WHERE permission='_a_2_intertriajewrite ";
		if($this->result=$db->Execute($this->sql)) {
			if($this->result->RecordCount()) {
				while($temp=$this->result->FetchRow()){
					$result[]=$temp;
				}
				return $result;
			}
		} else { return false; }

	}



}


?>
